package com.qf.cloud2203.getcoupons.coupons.service.impl;


import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.cloud2203.domain.constants.Constants;
import com.qf.cloud2203.domain.entity.Coupon;
import com.qf.cloud2203.getcoupons.coupons.mapper.CouponMapper;
import com.qf.cloud2203.getcoupons.coupons.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ada
 * @since 2023-03-10
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 发放优惠券
     * 每分钟查看一次
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void getCoupons() {
        List<Coupon> couponDBList = list(new QueryWrapper<Coupon>().eq("state", 1));
        ArrayList<Coupon> list = new ArrayList<>();
        if (couponDBList.size() == 0) {
            for (int i = 0; i < 20; i++) {
                Coupon coupon = new Coupon();
                coupon.setCouponId(UUID.randomUUID()+"");
                coupon.setPrice(50.0);
                coupon.setState(1);
                coupon.setCreatetime(new Date());
                coupon.setValid(new Date());
                list.add(coupon);
                redisTemplate.opsForList().rightPush(Constants.COUPON_KEY,coupon);
            }
            saveBatch(list);
        }
    }
}
